package obecto.mvc
{
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.IEventDispatcher;
    
    import obecto.core.FLGlobals;
    import obecto.event.FLEvent;
    
    [Event(name="creationComplete", type="obecto.event.FLEvent")]
    public class MVCSprite extends Sprite
    {
        [Bindable] protected var model : IModel;
        [Bindable] protected var controller : IController;
        [Bindable] protected var services : IServices;
        
        private var _view : IView;
        
        public function MVCSprite(target : IEventDispatcher = null)
        {
            super();
            
            FLGlobals.topLevelSprite.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
        }
        
        [Bindable]
        protected function get view():IView
        {
            return _view;
        }
        
        protected function set view(value:IView):void
        {
            if (_view) {
                removeChild(DisplayObject(_view));
            }
            
            _view = value;
            
            if (_view)
            {
                addChild(DisplayObject(_view));
            }
        }
        
        public function get displayObject() : DisplayObject
        {
            return view as DisplayObject;
        }
        
        protected function initializeDependencies() : void 
        {	
            view.model = model;
            
            controller.model = model;
            controller.view = view;
            if (services != null)
            {
                controller.services = services;
            }
            controller.initialize();
        }
        
        protected function handleEnterFrame(e : Event) : void
        {
            FLGlobals.topLevelSprite.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
            
            initializeDependencies();
            
            dispatchEvent(new FLEvent(FLEvent.CREATION_COMPLETE));
        }
        
    }
}